package net.doglog;

import javax.jdo.annotations.*;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class Comment {
	/*
	 * Using prefix is an old hack. Recently I found the followings in GAE documentation:
	 * 	@Persistent
	 * 	@Extension(vendorName="datanucleus", key="gae.parent-pk", value="true")
	 * 	private Key customerKey;
	 * See: http://code.google.com/intl/zh-CN/appengine/docs/java/datastore/transactions.html
	 */
	@NotPersistent
	private static final String prefix = "comment";
	
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;
	
	public Key getKey() {
		return key;
	}

	public long getId() {
		return Long.valueOf(key.getName().substring(prefix.length()));
	}

	@Persistent
	private long time;
	
	public long getTime() {
		return time;
	}
	
	@Persistent
	private Key ancestorKey;
	
	public Key getAncestorKey() {
		return ancestorKey;
	}
	
	@Persistent
	private Key parentKey;
	
	public Key getParentKey() {
		return parentKey;
	}

	@Persistent
	private String speaker;
	
	public String getSpeaker() {
		return speaker;
	}
	
	@Persistent(defaultFetchGroup = "true")
	private Text content;
	
	public String getContent() {
		return content.getValue();
	}
	
	public Comment(Post ancestor, Key parentKey, String speaker, String content) {
		this.time = System.currentTimeMillis();
		this.ancestorKey = ancestor.getKey();
		this.key = new KeyFactory.Builder(ancestorKey)
				.addChild(Comment.class.getSimpleName(), prefix + time).getKey();
		this.parentKey = parentKey;
		this.speaker = BlogUtil.escapeTag(speaker);
		this.content = new Text(BlogUtil.escapeAll(content));
	}
}
